package org.example.autoconfiguration;

import org.example.io.WriterTemplate;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.Charset;
import java.sql.SQLException;

/*
 *
 */
@Configuration
@ConditionalOnClass(WriterTemplate.class)
@EnableConfigurationProperties(WriterProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class WriterAutoConfiguration {
    private final WriterProperties properties;
    public WriterAutoConfiguration(WriterProperties properties)
    {
        this.properties=properties;
    }
    @Bean(destroyMethod = "close")
    //只有当单例的DataSource Bean 存在时才生效
    @ConditionalOnSingleCandidate(DataSource.class)
    @ConditionalOnMissingBean
    //比下一个配置WriterTemplate的方法的优先级更高
    @AutoConfigureOrder(99)
    public WriterTemplate writerTemplate(DataSource dataSource) throws SQLException
    {
        return new WriterTemplate(dataSource);
    }
    @Bean(destroyMethod = "close")
    //只有当前面的WriterTemplate未生效 该方法配置才生效
    @ConditionalOnMissingBean
    @AutoConfigureOrder(199)
    public WriterTemplate writerTemplate2() throws FileNotFoundException
    {
        File f=new File(this.properties.getDest());
        Charset charset=Charset.forName(this.properties.getCharset());
        return new WriterTemplate(f,charset);
    }
}
